// pages/user/shop-order-list/index.js
const app = getApp()
const order = require('../../../api/order')
import { initLoadMoreMixin } from '../../../utils/list-load-more'
import Toast from '../../../miniprogram/miniprogram_npm/vant-weapp/toast/toast'
import Dialog from '../../../miniprogram/miniprogram_npm/vant-weapp/dialog/dialog'

Page({

  /**
   * 页面的初始数据
   */
  data: {
    activeIndex: 0,
    tabsItem: [{
        name: '堂食订单',
        status: '',
        orderType: '6',
        cateringType: '1',
      },
      {
        name: '外卖订单',
        status: 0,
        status: '',
        orderType: '6',
        cateringType: '2',
      },
      {
        name: '自提订单',
        status: 0,
        status: '',
        orderType: '6',
        cateringType: '3',
      },
    ],

    searchValue: '',
    STATUS_TEXT: {
      '-1': "已取消",
      0: "待支付",
      1: "待接单",
      7: "待下单",
      8: "制作中",
      9: "制作完成",
      10: "配送中",
      2: "待收货",
      25: "部分发货",
      3: "待评价",
      4: "待退款",
      5: "售后中",
      6: "已完成",
    },
    teamId: '',
    statusLoad: '',
    seatShow:false,
    seatOrderId:'',
    seatNum:'',
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (event) {
    console.log(event)
    initLoadMoreMixin.call(this)
    let teamId = event.id

    let scene = event.scene;
    if(scene) {
      let tt = scene.split('-');
      if (tt.length > 0) {
        let obj = {};
        tt.forEach(item => {
          obj[item.split('!')[0]] = item.split('!')[1];
        })
        console.log(obj)
        this.setData({teamId: obj.sid || '', statusLoad: 2, activeIndex: 2})
      }
    } else {
      this.setData({teamId: teamId || ''})
    }
  },

  initData () {
    let tempStatus = this.data.statusLoad;
    const i = this.data.activeIndex
    const status = this.data.tabsItem[i].status
    let orderType = this.data.tabsItem[i].orderType
    let cateringType = this.data.tabsItem[i].cateringType
    if(this.data.pages.currPage == 1){
      this.data.items = [];
    };
    return app.requestUrl({
      url: order.ORDER_LIST,
      data: {
        limit: this.data.pages.perPage,
        offset: (this.data.pages.currPage - 1) * this.data.pages.perPage,
        tmid: this.data.teamId,
        status: tempStatus ? tempStatus : status,
        queryItem: this.data.searchValue,
        orderType:orderType,
        cateringType:cateringType
      }
    }).then(res => {
      const {
        rows,
        total
      } = res.data.data
      this.setData({
        items: this.data.items.concat(rows)
      });
      console.log(this.data.items);
      return {
        pageCount: rows.length,
        totalCount: total
      }
    })
  },
  handleTabClick (e) {
    this.setData({activeIndex: e.detail.index, statusLoad: ''})
    this.resetInit()
  },

  getStatusText (status) {
    return STATUS_TEXT[status] || ''
  },

  toOrderDetail (e) {

    const orderId = this.data.items[e.currentTarget.dataset.index].id
    wx.navigateTo({url: `/pages/user/order-info/order-info?payId=${orderId}`})
    // :todo
    // this.$router.push({
    //   name: "payment",
    //   params: {
    //     payId: orderId
    //   }
    // })
  },
  toOrderGet (i) {
    app.requestUrl({url: order.ORDER_CONFIRMRECEIVED, data: {orderId: this.data.items[i].id}}).then(res => {
      // this.items[i].status=3
      this.setData({[`items[${i}].status`]: 3})
    })
    //参数 orderId 订单id
  },
  //商家接单
  toOrderGet_merchantReceieveOrder (e) {
    let _this = this
    let item = _this.data.items[e.currentTarget.dataset.index]
    Dialog.confirm({
      message: "确认接单？"
    }).then(() => {
      app.requestUrl({method: 'POST',url: order.ORDER_RECEIVE_TAKEOUT_FOOD, data: {orderId: item.id}}).then(res => {
        let status = 'items[' + e.currentTarget.dataset.index + '].status'
        _this.setData({[status]: 7})
      })
    });
  },
  //商家向后厨下单
  toOrderGet_merchantPlaceForBackKitchen (e) {
    let _this = this
    let item = _this.data.items[e.currentTarget.dataset.index]
    Dialog.confirm({
      message: "确认向后厨下单？"
    }).then(() => {
        app.requestUrl({method: 'POST',url: order.ORDER_PLACE_FOR_BACK_KITCHEN, data: {orderId: item.id}}).then(res => {

          let status = 'items[' + e.currentTarget.dataset.index + '].status'
          _this.setData({[status]: 8})
        })
    });
  },
  //商家完成制作接口
  toOrderGet_merchantFinishMakeOrder (e) {
    let _this = this
    let item = _this.data.items[e.currentTarget.dataset.index]
    Dialog.confirm({
      message: "确认完成制作？"
    }).then(() => {
      app.requestUrl({method: 'POST',url: order.ORDER_FINISH_MAKE, data: {orderId: item.id}}).then(res => {
  
        let status = 'items[' + e.currentTarget.dataset.index + '].status'
        _this.setData({[status]: 9})
      })
    });
  },
  //商家将配送订单同步到餐道
  toOrderGet_syncCandaoOrder (e) {
    let _this = this
    let item = _this.data.items[e.currentTarget.dataset.index]
    Dialog.confirm({
      message: "确认呼叫骑手？"
    }).then(() => {
      app.requestUrl({url: order.ORDER_SYNC_CANDAO_ORDER, data: {orderId: item.id}}).then(res => {
        let status = 'items[' + e.currentTarget.dataset.index + '].status'
        _this.setData({[status]: 9})
      })
    });
  },
  //商家将配送订单同步到餐道
  toOrderGet_merchantSyncCandaoDeliveryInfo (e) {
    let _this = this
    let item = _this.data.items[e.currentTarget.dataset.index]
    Dialog.confirm({
      message: "确认呼叫骑手？"
    }).then(() => {
      app.requestUrl({url: order.ORDER_SYNC_CANDAO_DELIVERYINFO, data: {orderId: item.id}}).then(res => {
        let status = 'items[' + e.currentTarget.dataset.index + '].status'
        _this.setData({[status]: 9})
      })
    });
    
  },
  toOrderGet_sendGoods (e) {
    let _this = this
    let item = _this.data.items[e.currentTarget.dataset.index]
    Dialog.confirm({
      message: "确认发货？"
    }).then(() => {
      app.requestUrl({url: order.ORDER_SENDGOODS, data: {orderId: item.id}}).then(res => {

        let status = 'items[' + e.currentTarget.dataset.index + '].status'
        _this.setData({[status]: 2})
      })
    });
  },
  //确认收货
  toOrderGet_receiving(e){
    let item = this.data.items[e.currentTarget.dataset.index]
    let cateringtype = e.currentTarget.dataset.cateringtype
    let tipMsg = '确认已收到商品？';
    if(cateringtype != 2){
      tipMsg = '确认取餐？';
    }
    Dialog.confirm({
      message: tipMsg
    }).then(() => {
        app.requestUrl({url: order.ORDER_CONFIRMRECEIVED, data: {orderId: item.id}}).then(res => {
          let status = 'items[' + e.currentTarget.dataset.index + '].status'
          this.setData({[status]: 3})
        })
    });
  },
  //到货提醒
  arrivalReminder(event){
    let item = this.data.items[event.currentTarget.dataset.index]
    app.requestUrl({
      method: 'POST',
      url: '/wxapi/send/arrivalTemplate',
      data: {
        ordeIds: [item.id]
      },
      header: {
        'Content-Type': 'application/json;charset=UTF-8',
        'Authorization': wx.getStorageSync('authToken') || 'empty-token'
      },
    }).then(res => {
      wx.showToast({
        title: res.data.msg,
        icon: 'none'
      })
    }).catch(res => {
    })
  },

  onSearch () {
    this.resetInit()
  },

  // addWorkOrder(goods) {
  //   this.$router.push({
  //     name: "add-work-order",
  //     query: {
  //       orderId: goods.orderid,
  //       goodsId: goods.id,
  //       goodsPrice: goods.marketprice,
  //       goodsNum: goods.total
  //     }
  //   });
  // },
  // cancelWorkOrder(goods) {

  //   Dialog.confirm({
  //         message: "是否确认撤销售后申请",
  //         cancelButtonText: "取消"
  //       }).then(() => {
  //           app.requestUrl(WORKORDER_CANCEL, {id: goods.workId}).then(res => {
  //           if (res.data.data === 1) {
  //             this.$toast.success('工单撤销成功');
  //             this.resetInit();
  //           }
  //         });
  //       });
  // },
  // workOrder(goods) {
  //   this.$router.push({name: 'work-order', params: {workId: goods.workId}});
  // },
  //检查商品售后状态
  goodsStatus (goods) {
    if (this.teamId != this.user.id) {
      return 0
    }

    if (goods.status == 2 || goods.status == 3) {
      return 1
    }

    if (goods.status == 5) {
      return 2
    }
  },
  // 点击显示座位号
  ShowSeatNum(e){
    console.log(e);
    this.setData({
      seatShow:true,
      seatOrderId:e.currentTarget.dataset.id,
    })
  },
  // 获取座位号value
  selectSeatNum(e){
    this.setData({
      seatNum:e.detail.value,
    })
  },
  CloseSeatNum(){
    this.setData({
      seatShow:false,
    })
  },

  sureSeatNum(){
    let that = this;
    if(that.data.seatNum == ''){
      Toast('请输入座位号');
      return;
    }else{
      app.requestUrl({
        method: 'POST',
        url: '/wxapi/order/alterSeatNum',
        data: {
          orderId:that.data.seatOrderId,
          seatNum:that.data.seatNum,
        },
        load: 0
      }).then((res)=>{
        that.setData({
          seatShow:false,
          ['pages.currPage']:1,
        });
        Toast(res.data.msg);
        that.initData();
      })
    }
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    let user = app.getUser();
    if(user.id == null){
      wx.navigateTo({  url: '/pages/login/login' })
      return;
    } else if(user.isteam != 3 && user.isClerk != 1){
      wx.switchTab({ url: '/pages/index/index' })
      return;
    }
    this.resetInit()
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})
